﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：庄金冬 
    //
    // 文件名：BLL_Goods.cs
    // 文件功能描述：商品操作业务逻辑类,,实现接口IBLL_Company,继承自类MarshalByRefObject
    // 创建标识：庄金冬2009-03-06
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using System.Data;
using HZ.DrugTrade.DAL;
using HZ.Common;
namespace HZ.DrugTrade.BLL
{


    /// <summary>
    /// 商品操作业务逻辑类,实现接口IBLL_Company,继承自类MarshalByRefObject
    /// </summary>
    public class BLL_Goods : MarshalByRefObject, IBLL_Goods
    {
        #region IBLL_Goods Members
        /// <summary>
        /// 获取所有产品信息
        /// </summary>
        /// <returns>所有产品信息</returns>
        public IList<Model.View.Goods> GetAllGoods()
        {
            int totalrecord = 0;
            return GetGoodsByWhere(null, 1, 0, out totalrecord);
        }

        /// <summary>
        /// 添加产品信息（0失败;1成功）
        /// </summary>
        /// <param name="goods">产品信息</param>
        /// <returns>0失败;1成功</returns>
        /// <remarks>
        /// ID可以为空，其余字段一律不得为空
        /// 
        /// </remarks>
        public int AddGoods(Model.Goods goods)
        {
            int state = HZ.Data.DAL_Helper.OperateTable(goods, HZ.Data.TableOperator.Insert);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("添加产品信息：{0};处理时间:{1};)", goods.GoodsID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }

        /// <summary>
        /// 更新产品信息（0失败;1成功）
        /// </summary>
        /// <param name="goods">产品信息</param>
        /// <returns>0失败;1成功</returns>
        public int UpdateGoods(Model.Goods goods)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                #region 产品基本信息

                //更新商品信息
                //string sql = HZ.Data.DAL_Helper.GetUpdateSql(goods);
                //sh.ExecuteNonQuery(sql);
                HZ.Data.DAL_Helper.OperateTableSQL<Model.Goods>(goods, HZ.Data.TableOperator.Update, sh);
                #endregion

                #region 更新采购目录信息
                string sql = string.Format("Update TB_ProcureCatalog SET ProcurePrice = '{0}',SortSource = '{1}' WHERE GoodsID ='{2}' ", HZ.Fun2.GetProcurePrice(goods.LimitPrice), goods.Source, goods.GoodsID);
                sh.ExecuteNonQuery(sql);
                #endregion
                sh.CommitTrans();

                //BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 通用名全称：{0} 国家限价：{1} 产品属性：{2}", goods.ProductName, goods.LimitPrice, (goods.Source.Value == 2) ? "备案产品" : "非中标") });
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 产品名称：{0} 国家限价：{1}  ", goods.GoodsName, goods.LimitPrice), ClientIP = HZ.Fun.GetClientIP() });//2011-0114 ml 去掉产品属性
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Goods", "出现SqlException", ex);
                return 2;
            }
        }


        ///// <summary>
        ///// 条件查询产品
        ///// </summary>
        ///// <param name="where">查询用实体</param>
        ///// <param name="currentPage">当前页</param>
        ///// <param name="pageSize">每页显示记录数</param>
        ///// <param name="totalRecord">（输出参数）总记录数目</param>
        ///// <returns></returns>
        //public Model.Goods GetGoodsByID(string goodsID)
        //{
        //    Model.Goods goods = new Model.Goods() { GoodsID = goodsID };
        //    goods = HZ.Data.DAL_Helper.GetModelByID(goods);
        //    return goods;
        //}


        /// <summary>
        /// 条件查询采购产品
        /// </summary>
        /// <param name="where">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Model.View.Goods> GetGoodsByWhere(Model.Query.Goods where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Goods.GetGoodsByWhere(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 条件查询非采购产品
        /// </summary>
        /// <param name="where">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<Model.View.Goods> GetUnGoodsByWhere(Model.Query.Goods where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Goods.GetUnGoodsByWhere(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 条件查询所有产品
        /// </summary>
        /// <param name="where">查询用实体</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="totalRecord">（输出参数）总记录数目</param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.Goods> GetAllGoodsByWhere(HZ.DrugTrade.Model.Query.Goods where, int currentpage, int pagesize, out int totalrecord)
        {
            return DAL.DAL_Goods.GetAllGoodsByWhere(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 获取一条中标或不中标商品
        /// </summary>
        /// <param name="goodsID">产品编号</param>
        /// <returns>产品实体</returns>
        public HZ.DrugTrade.Model.View.Goods GetGoodsByID(string goodsID)
        {
            HZ.Common.ThrowHelper.Throw(!string.IsNullOrEmpty(goodsID), "产品编号不能空");
            return DAL.DAL_Goods.GetGoodsByID(goodsID);
        }



        /// <summary>
        /// 更新产品信息（0失败;1成功）
        /// </summary>
        /// <param name="goods">产品信息</param>
        /// <param name="model">jixing</param>
        /// <returns>0失败;1成功</returns>
        public int UpdateGoods(Model.Goods goods, string Operator)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                #region 产品基本信息

                //更新商品信息
                //string sql = HZ.Data.DAL_Helper.GetUpdateSql(goods);
                //sh.ExecuteNonQuery(sql);
                HZ.Data.DAL_Helper.UpdateModel<Model.Goods>(goods);
                //HZ.Data.DAL_Helper.OperateTableSQL<Model.Goods>(goods,HZ.Data.TableOperator.Update);
                #endregion

                #region 更新采购目录信息
                string sql2 = string.Format("Update TB_ProcureCatalog SET SortSource={1} WHERE GoodsID ='{0}' ", goods.GoodsID, goods.Source);
                sh.ExecuteNonQuery(sql2);
                #endregion
                sh.CommitTrans();

                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 产品名称：{0} 国家限价：{1}  操作：{2},修改人：{3};修改时间：{4} ", goods.GoodsName, goods.LimitPrice, sql2, Operator, DateTime.Now.ToString()), ClientIP = HZ.Fun.GetClientIP() });
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Goods", "出现SqlException", ex);
                return 0;
            }
        }
        /// <summary>
        /// 增加目录信息（0失败;1成功） add by zdc 升级后View_Procurecatalog_TB
        /// </summary>
        /// <param name="vpt"></param>
        /// <param name="Operator"></param>
        /// <returns></returns>
        public int AddVPT(View_Procurecatalog_TB vpt, string Operator)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans();
                string sql=string.Empty;
                #region 更新采购目录视图表信息 add by View_Procurecatalog_tb 系统升级后添加
                vpt.Price = 0;
                vpt.PinyinCode = HZ.Common.zhHansUtil.GetSpellHeads(vpt.ProductName);
                int count = HZ.Data.DAL_Helper.InsertModel<View_Procurecatalog_TB>(vpt);
                string sqlcount = " select count(ProcureCatalogID) from TB_AreaProcureCataLog where ProcureCatalogID='" + vpt.ProcureCatalogID + "'";
                int cc = int.Parse(HZ.Data.DbHelperFactory.Create().ExecuteScalar(sqlcount).ToString());
                if (cc == 0)
                {
                    string sqlstr = @"  Insert  Into TB_AreaProcureCataLog Select '" + vpt.ProcureCatalogID + "','" +
                        vpt.ProjectID + "','" + vpt.GoodsID + "',AreaID,"+vpt.ProcurePrice+" From TB_Area Where mod(AreaID,100)=0 and  AREAID>150000 and AREAID<160000";
                    HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(sqlstr);
                }
                //sh.ExecuteNonQuery(sql);

                #endregion
                sh.CommitTrans();
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 通用名全称：{0}  操作：{1},添加人：{2};添加时间：{3} ", vpt.ProductName, sql, Operator, DateTime.Now.ToString()), ClientIP = HZ.Fun.GetClientIP() });
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Goods", "出现SqlException", ex);
                throw;
            }
        }
        /// <summary>
        /// 更新目录信息（0失败;1成功） add by zdc 升级后View_Procurecatalog_TB
        /// </summary>
        /// <param name="goods">产品信息</param>
        /// <returns>0失败;1成功</returns>
        public int UpdateVPT(View_Procurecatalog_TB vpt, string Operator) 
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                #region 产品基本信息

                //更新商品信息
                //string sql = HZ.Data.DAL_Helper.GetUpdateSql(goods);
                //sh.ExecuteNonQuery(sql);
                HZ.Data.DAL_Helper.UpdateModel<Model.View_Procurecatalog_TB>(vpt);
                //HZ.Data.DAL_Helper.OperateTableSQL<Model.Goods>(goods,HZ.Data.TableOperator.Update);
                #endregion

                #region 更新采购目录信息
                string sql2 = string.Format("Update TB_ProcureCatalog SET SortSource={1} WHERE GoodsID ='{0}' ", vpt.GoodsID, vpt.SortSource);
                sh.ExecuteNonQuery(sql2);
                #endregion
                sh.CommitTrans();

                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 通用名全称：{0}  操作：{1},修改人：{2};修改时间：{3} ", vpt.ProductName, sql2, Operator, DateTime.Now.ToString()), ClientIP = HZ.Fun.GetClientIP() });
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_Goods", "出现SqlException", ex);
                return 0;
            }
        }

        #endregion


        #region 添加中标产品 20100119
        /// <summary>
        /// 更新产品信息（0失败;1成功）
        /// </summary>
        /// <param name="goods">产品信息</param>
        /// <returns>0失败;1成功</returns>
        public int AddGoods(Model.Goods goods, string Operator)
        {
            //定义中间数据 ID
            int result = 0;

            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                string sql = string.Empty;

                #region 生产企业

                sql = "SELECT  CompanyId FROM TB_Company WHERE rownum<=1 and CompanyID='" + goods.CompanyID_SC + "'";
                object objCompanyID_SC = sh.ExecuteScalar(sql);

                if (objCompanyID_SC == null)
                {
                    //插入新的生产企业
                    sql = string.Format("INSERT INTO TB_Company ( CompanyID,CompanyName,CompanyType) VALUES( '{0}','{1}','{2}')", goods.CompanyID_SC, goods.CompanyName_SC, goods.CompanyID_SC.Substring(0, 1).ToUpper() == "S" ? "0" : "1");
                    sh.ExecuteNonQuery(sql);

                    sql = "SELECT CompanyID FROM TB_CompanyInfo WHERE rownum<=1 and CompanyName='" + goods.CompanyName_SC + "'";
                    object objCompanyName_SC = sh.ExecuteScalar(sql);

                    if (objCompanyName_SC == null)
                    {
                        //插入新的生产企业
                        sql = string.Format("INSERT INTO TB_CompanyInfo ( CompanyID,CompanyName) VALUES( '{0}','{1}')", goods.CompanyID_SC, goods.CompanyName_SC);

                        sh.ExecuteNonQuery(sql);
                    }
                    else
                    {
                        result = 3;
                        new Exception();
                    }
                }

                #endregion

                #region 投标企业

                sql = "SELECT CompanyId FROM TB_Company WHERE rownum<=1 and CompanyID='" + goods.CompanyID_TB + "'";
                object objCompanyID_TB = sh.ExecuteScalar(sql);

                if (objCompanyID_TB == null)
                {
                    //插入新的生产企业
                    sql = string.Format("INSERT INTO TB_Company ( CompanyID,CompanyName,CompanyType) VALUES( '{0}','{1}','{2}')", goods.CompanyID_TB, goods.CompanyName_TB, goods.CompanyID_TB.Substring(0, 1).ToUpper() == "S" ? "0" : "1");

                    sh.ExecuteNonQuery(sql);

                    sql = "SELECT   CompanyID FROM TB_CompanyInfo WHERE rownum<=1 and CompanyName='" + goods.CompanyName_TB + "'";
                    object objCompanyName_TB = sh.ExecuteScalar(sql);

                    if (objCompanyName_TB == null)
                    {

                        //插入新的生产企业
                        sql = string.Format("INSERT INTO TB_CompanyInfo ( CompanyID,CompanyName) VALUES( '{0}','{1}')", goods.CompanyID_TB, goods.CompanyName_TB);

                        sh.ExecuteNonQuery(sql);
                    }
                    else
                    {
                        result = 4;
                        new Exception();
                    }
                }

                #endregion

                #region 产品信息

                goods.PinyinCode = HZ.Common.zhHansUtil.GetSpellHeads(goods.GoodsName);

                sql = "SELECT goodsid FROM TB_Goods WHERE rownum<=1 and goodsid='" + goods.GoodsID + "'";
                object objgoodsid = sh.ExecuteScalar(sql);

                if (objgoodsid == null)
                {
                    //插入商品信息
                    sql = HZ.Data.DAL_Helper.GetInsertSql(goods);
                    sh.ExecuteNonQuery(sql);
                }
                else
                {
                    result = 2;
                    new Exception();
                }


                #endregion
                #region 更新采购目录信息

                sql = string.Format(@"INSERT INTO TB_ProcureCatalog
           (ProcureCatalogID,ProjectID,GoodsID,ProcurePrice,IsUsing,IsFlowing,SortSource)
     VALUES('{0}','0001','{1}',{2},1,0,'{3}')", goods.GoodsID, goods.GoodsID, goods.BidPrice, goods.Source.ToString());

                sh.ExecuteNonQuery(sql);

                #endregion
                
                sh.CommitTrans();

                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("基础产品修改 产品名称：{0} 国家限价：{1}  操作：{2},添加人：{3};修改时间：{4} ", goods.GoodsName, goods.LimitPrice, sql + ";", Operator, DateTime.Now.ToString()), ClientIP = HZ.Fun.GetClientIP() });
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("AddGoods", "出现SqlException", ex);
                return result;
            }
        }
        #endregion


        public int DelGoods(string goods, string Operator)
        {
            //定义中间数据 ID
            int result = 0;

            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                #region 删除中标产品
                string sql = string.Format(@"
                                            begin
                                            DELETE FROM TB_HospitalProcureCatalog where ProcureCatalogID='{0}';
                                            DELETE FROM TB_AreaDistribution where ProcureCatalogID='{0}';
                                            DELETE FROM TB_SelectRelation where ProcureCatalogID='{0}';
                                            DELETE FROM TB_ProcureCatalog where GoodsID='{0}';
                                            DELETE FROM TB_Goods where GoodsID='{0}'; end;", goods);


                sh.ExecuteNonQuery(sql);

                #endregion

                sh.CommitTrans();

                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog() { OperateMessage = string.Format("删除产品信息 产品流水号：{0}；删除人：{1};删除时间：{2} ", goods, Operator, DateTime.Now.ToString()), ClientIP = HZ.Fun.GetClientIP() });
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("delGoods", "出现SqlException", ex);
                return result;
            }
        }

        /// <summary>
        /// 获取生产企业对应产品
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public System.Data.DataTable GetGoods(string userid)
        {
            return DAL.DAL_Goods.GetGoods(userid);
        }
        /// <summary>
        /// 根据产品编号查询产品信息
        /// add by Meng 2013-03-25
        /// </summary>
        /// <param name="goodsid"></param>
        /// <returns></returns>
        public HZ.DrugTrade.Model.Goods GetGoodsInfoByWhere(string goodsid)
        {
            return DAL.DAL_Goods.GetGoodsInfoByWhere(goodsid);
        }
        /// <summary>
        /// 条件查询商品耗材
        /// </summary>
        /// <param name="objquery"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.TB_Goods_GZHC> GetGoodsByWhere_GZHC(object objquery, int currentPage, int pageSize, out int totalRecord)
        {
            return HZ.Data.DAL_Helper.GetPagedModel<HZ.DrugTrade.Model.View.TB_Goods_GZHC>(objquery, currentPage, pageSize, out totalRecord);
        }
        /// <summary>
        /// 更新产品信息
        /// </summary>
        /// <param name="goods"></param>
        /// <returns></returns>
        public int UpdateGoodsInfo(HZ.DrugTrade.Model.Goods goods)
        {
            int state = DAL.DAL_Goods.UpdateGoodsInfo(goods);
            if(state == 1)
            {
                BLL_Log.Instance.AddKeyOperationLog(new KeyOperationLog { OperateMessage = string.Format("更新产品信息：{0};处理时间:{1};)", goods.GoodsID, DateTime.Now.ToString()), ClientIP = HZ.Fun2.GetClientIP() });
            }
            return state;
        }
        /// <summary>
        /// 获取限价列表
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public DataTable GetLimitPriceByWhere(string where, int currentPage, int pageSize, out int totalRecord)
        {
            return DAL.DAL_Goods.GetLimitPriceByWhere(where, currentPage, pageSize, out totalRecord);
        }
        /// <summary>
        /// 根据产品编号获取限价信息
        /// </summary>
        /// <param name="goodsid"></param>
        /// <returns></returns>
        public LimitedPrice GetLimitedPriceByID(string goodsid)
        {
            return DAL.DAL_Goods.GetLimitedPriceByID(goodsid);
        }
        /// <summary>
        /// 更新限价
        /// </summary>
        /// <param name="lp"></param>
        /// <returns></returns>
        public int GetUpdatelimitPrice(LimitedPrice lp)
        {
            return DAL.DAL_Goods.GetUpdatelimitPrice(lp);
        }
        /// <summary>
        /// 企业确认限价
        /// </summary>
        /// <param name="Goodsid"></param>
        /// <returns></returns>
        public int GetConfirmLimitPrice(string Goodsid)
        {
            return DAL.DAL_Goods.GetConfirmLimitPrice(Goodsid);
        }
    }
}
